#include "log_fac.h"
#include <log_console_output.h>
#include <log_file_output.h>
#include <xlog_format.h>
#include <xconfig.h>
#include <iostream>
#include <log_xml_format.h>
using namespace std;

#define LOGTYPE "console"
#define LOGFILE "log.txt"
#define LOGLEVEL "debug"
#define LOGLFORMAT "default"

void LogFac::config(const std::string &conf_file)
{
    XConfig conf;
    auto re = conf.Read(conf_file);

    string log_type = LOGTYPE;
    string log_file = LOGFILE;
    string log_level = LOGLEVEL;
    string log_format = LOGLFORMAT;

    if (re)
    {
        log_type = conf.Get("log_type");
        log_file = conf.Get("log_file");
        log_level = conf.Get("log_level");
        log_format = conf.Get("log_format");

        if (log_type.empty())
            log_type = LOGTYPE;
        if (log_file.empty())
            log_file = LOGFILE;
        if (log_level.empty())
            log_level = LOGLEVEL;
        if (log_format.empty())
            log_format = LOGLFORMAT;
    }
    else
    {
        cout << "open file failed! " << conf_file << endl;
    }

    if (log_type == "file")
    {
        auto fout = new LogFileOutput;

        if (!fout->Open(log_file))
        {
            cout << "open file failed! " << log_file << endl;
        }
        logger_.SetOutput(fout);
    }

    if (log_level == "info")
    {
        logger_.SetLevel(XLog::INFO);
    }
    else if (log_level == "error")
    {
        logger_.SetLevel(XLog::ERROR);
    }
    else if (log_level == "fatal")
    {
        logger_.SetLevel(XLog::FATAL);
    }

    if (log_format == "xml")
    {
        logger_.SetFormat(new LogXMLFormat);
    }
}

void LogFac::Init(const std::string &conf_file)
{
    logger_.SetFormat(new XLogFormat);
    logger_.SetOutput(new LogConsoleOutput);
    config(conf_file);
}

LogFac &LogFac::Instance()
{
    static LogFac fac;
    return fac;
}
